package com.yy.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.filter.OrderedFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;

/**
 * Author young
 * Date 2022/12/27 16:16
 * Description: 自定义网关过滤器
 * @author young
 */
@Component
@Slf4j
public class FilterConfig implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("创建自定义网关过滤器，时间为{}", LocalDateTime.now());
        //获取请求中的信息，需带有参数为young的信息请求才能生效    http://localhost:9527/payment/client/lb?young=1
        String name = exchange.getRequest().getQueryParams().getFirst("young");
        //进行判断过滤
        if (name==null){
            log.info("用户名不存在或者错误");
            //响应一个结果
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
